const obj = {
    name: "echo",
    age: 18
};
let activeFn = null;
class Depend {
    constructor() {
        this.arrFn = new Set();
    }
    depend() {
        if (activeFn)
            this.arrFn.add(activeFn);
    }
    notify() {
        this.arrFn.forEach(fn => fn());
    }
}


const depend = new Depend();
const weakmap = new WeakMap();

function getTarget(obj, key) {
    let map = weakmap.get(obj);
    if (!map) {
        map = new Map();
        weakmap.set(obj, map);
    }
    let depend = map.get(key);
    if (!depend) {
        depend = new Depend();
        map.set(key, depend);
    }
    return depend;
}

function reactive(obj) {
    const objProxy = Proxy(obj, {
        set: function (target, property, value, receiver) {
            const depend = getTarget(target, property);
            depend.depend();
            Reflect.set(target, property, value, receiver);
        },
        get: function (target, property, receiver) {
            const depend = getTarget(target, property);
            depend.notify();
            Reflect.get(target, property, receiver);
        }
    });
    return objProxy;
}

const objProxy = reactive(obj);

function watchFn(fn) {
    activeFn = fn;
    fn();
    activeFn = null;
}

function foo() {
    console.log("这里是foo函数");
    console.log(objProxy.name);
}
watchFn(foo);
watchFn(() => {
    console.log("这里是bar函数");
    console.log(objProxy.age);
});
objProxy.age = 12;
objProxy.name = "er";